package cn.est.serviceImpl;

import cn.est.constants.Constants;
import cn.est.constants.MathUtil;
import cn.est.dto.AppointmentReq;
import cn.est.dto.EvaluateDto;
import cn.est.dto.Page;
import cn.est.mapper.MaintainOrderMapper;
import cn.est.pojo.Appointment;
import cn.est.pojo.Evaluate;
import cn.est.pojo.MaintainOrder;
import cn.est.pojo.PayOrder;
import cn.est.service.*;
import cn.est.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;

@Service
public class MaintainOrderServiceImpl implements MaintainOrderService {

    @Autowired
    private MaintainOrderMapper maintainOrderMapper;

    @Autowired
    private AppointmentService appointmentService;

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private MaintainOrderFlowService maintainOrderFlowService;

    @Autowired
    private EvaluateService evaluateService;

    public MaintainOrder getMaintainOrderById(Long id) {
        return maintainOrderMapper.getMaintainOrderById(id);
    }

    public List<MaintainOrder> getMaintainOrderListByMap(Map<String, Object> param) {
        return maintainOrderMapper.getMaintainOrderListByMap(param);
    }

    public Integer getMaintainOrderCountByMap(Map<String, Object> param) {
        return maintainOrderMapper.getMaintainOrderCountByMap(param);
    }

    public Integer qdtxAddMaintainOrder(MaintainOrder maintainOrder) {
        maintainOrder.setCreatdTime(new Date());
        return maintainOrderMapper.insertMaintainOrder(maintainOrder);
    }

    public Integer qdtxModifyMaintainOrder(MaintainOrder maintainOrder) {
        maintainOrder.setUpdatedTime(new Date());
        return maintainOrderMapper.updateMaintainOrder(maintainOrder);
    }

    public Integer qdtxDeleteMaintainOrderById(Long id) {
        return maintainOrderMapper.deleteMaintainOrderById(id);
    }

    public Integer qdtxBatchDeleteMaintainOrder(String ids) {
        Map<String, List<String>> param = new HashMap<String, List<String>>();
        String[] paramArrays = ids.split(",");
        List<String> idList = new ArrayList<String>();
        for (String temp : paramArrays) {
            idList.add(temp);
        }
        param.put("ids", idList);
        return maintainOrderMapper.batchDeleteMaintainOrder(param);
    }

    public Page<MaintainOrder> queryMaintainOrderPageByMap(Map<String, Object> param, Integer pageNo, Integer pageSize) {
        Integer total = maintainOrderMapper.getMaintainOrderCountByMap(param);
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<MaintainOrder> maintainOrderList = maintainOrderMapper.getMaintainOrderListByMap(param);
        page.setList(maintainOrderList);
        return page;
    }

   @Override
    @Transactional
    public String submit(AppointmentReq appointmentReq, Integer eId, Long mid) throws ParseException {

        //保存预约的信息
        Appointment appointment =new Appointment(appointmentReq);
        appointmentService.qdtxAddAppointment(appointment);
        //保存维修订单信息  --->订单表   订单流水表
        return   save(mid,eId,appointmentReq.getUserId());
    }

    @Override
    @Transactional
    public int finishPay(String aliTradeNo, String payNo, String totalAmount) {
          int  succ=0;
        MaintainOrder maintainOrder=null;
       //1.数据校验，查看是否有这个订单
            Map map1 =new HashMap();
            map1.put("payNo",payNo);
           List<PayOrder>  payOrderList=payOrderService.getPayOrderListByMap(map1);
            if(payOrderList==null||payOrderList.size()==0){
                return 0;
            }
            PayOrder payOrder=payOrderList.get(0);
            Map map =new HashMap();
            map.put("orderNo",payOrder.getOrderNo());
        //2.获取订单
            List<MaintainOrder> maintainOrderList=maintainOrderMapper.getMaintainOrderListByMap(map);
            if (!maintainOrderList.isEmpty()){
        //3.查询订单状态，如果预约维修装台，订单表改成已支付定金状态
               maintainOrder =  maintainOrderList.get(0);
               if(maintainOrder.getStatus()== Constants.Order.MaintainStatus.APPOINT){
                   maintainOrder.setStatus(Constants.Order.MaintainStatus.PAY_DEPOSIT);
               }
              maintainOrder.setUpdatedTime(DateUtils.getCurrentDate(DateUtils.YYYY_MM_DD_HH_MM_SS));
              succ=maintainOrderMapper.updateMaintainOrder(maintainOrder);
            }
        //4.修改交易订单表，业务表数据 pay_order表中的数据
            payOrderService.finishPay(payOrder,aliTradeNo);

        //5.修改流水业务表数据
            maintainOrderFlowService.saveByMaintainOrder(maintainOrder);

        return succ;
    }


    public String save(Long mid,Integer eid,Long uid) throws ParseException {
            //1.获取估算对象
              EvaluateDto evaluateDto = evaluateService.getEById(eid);
              Evaluate evaluate=evaluateDto.getEvaluate();
        //2.封装订单信息到MaintainOrder对象
              MaintainOrder maintainOrder =new MaintainOrder();
              maintainOrder.setUserId(uid);
              maintainOrder.setModelId(mid);
              maintainOrder.setEvaluateId(new Long(eid));
              maintainOrder.setSubscription(evaluate.getSubscription());
              maintainOrder.setPrice(evaluate.getPrice());
              maintainOrder.setStatus(Constants.Order.MaintainStatus.APPOINT);
              maintainOrder.setIsComment(Constants.Order.Comment.isYestComment);
              maintainOrder.setCreatdTime(new Date());
              maintainOrder.setIsDelete(Constants.EST_NOT);
              maintainOrder.setCreatedUserId(uid);
          //创建一个OrderNo
              maintainOrderMapper.insertMaintainOrder(maintainOrder);
              String orderNo =createOrderNo(maintainOrder.getId().toString());
              maintainOrder.setOrderNo(orderNo);
        //3.保存订单信息
              maintainOrderMapper.updateMaintainOrder(maintainOrder);

            //4.保存订单流水信息
             int result= maintainOrderFlowService.saveByMaintainOrder(maintainOrder);

             return orderNo;
    }


    public String createOrderNo(String orderId) throws ParseException {
        StringBuffer orderNo =new StringBuffer(DateUtils.format(new Date(),DateUtils.YYYYMMDDHHMMSS));
        orderNo.append(MathUtil.randomCode());
        for (int i=10-orderId.length();i>0;i--){
            orderNo.append("0");
        }
        orderNo.append(orderId);
    //验证orderNo唯一性
        Map map =new HashMap();
        map.put("orderNo",orderNo.toString());
        List<MaintainOrder> orderList=maintainOrderMapper.getMaintainOrderListByMap(map);
        if(orderList.isEmpty()){
           return orderNo.toString();
        }
        return createOrderNo(orderId);
    }


}
